package com.xunua.myaudioandvideolearning.camera1

import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.util.Log
import com.xunua.myaudioandvideolearning.h264Packaging.FileUtils
import java.lang.Exception

/**
 * @author: linxunyou
 * @description:
 * @date :2022/5/7 13:42
 **/
private const val TAG = "H264CameraEncoder"
class H264CameraEncoder(var width:Int,var height:Int) {
    private var index:Long=0L
    private lateinit var mediaCodec: MediaCodec

    fun startLive(){
        try {
            mediaCodec= MediaCodec.createEncoderByType("video/avc")
            var mediaFormat = MediaFormat.createVideoFormat("video/avc", width, height)
            mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE,width*height)
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE,15)
            mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL,2)
            mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible)
            mediaCodec.configure(mediaFormat,null,null,MediaCodec.CONFIGURE_FLAG_ENCODE)
            mediaCodec.start()
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    fun encodeFrame(input: ByteArray) {
        //输入
        val inputBufferIndex = mediaCodec.dequeueInputBuffer(1000 * 10)
        val bufferInfo = MediaCodec.BufferInfo()
        if (inputBufferIndex>=0){
            val inputBuffer = mediaCodec.getInputBuffer(inputBufferIndex)
            inputBuffer?.clear()
            inputBuffer?.put(input)
            mediaCodec.queueInputBuffer(inputBufferIndex,0,input.size, computePts(),0)
            index++
        }

        //输出
        val outputIndex = mediaCodec.dequeueOutputBuffer(bufferInfo, 1000 * 100)
        if (outputIndex>=0){
            val outputBuffer = mediaCodec.getOutputBuffer(outputIndex)
            val data = ByteArray(bufferInfo.size)
            outputBuffer?.get(data)
            FileUtils.writeBytes(data)
            FileUtils.writeContent(data)
            mediaCodec.releaseOutputBuffer(outputIndex,false)
        }
    }

    private fun computePts():Long{
        return 1000L*1000L/15L*index
    }
}